package cn.itsource.utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

//基于数据库的分布式锁实现
public class DbGoodsLock {

    private Long goodsId = null;
    public DbGoodsLock(Long goodsId) {
        this.goodsId = goodsId;
    }

    /**
     * 能插入就能获取获取锁
     * @return
     */
    public  boolean  trylock(){
        Connection connection = null;
        try{
           connection  = JDBCUtils.getConnection();
            Statement statement = connection.createStatement();

            statement.execute("insert into t_goods_lock(id) values("+this.goodsId+")");
            System.out.println(Thread.currentThread().getName()+"加锁，插入数据 goodsId="+goodsId);
            return true;
        }catch (Exception e) {
            //e.printStackTrace();
            System.out.println(Thread.currentThread().getName()+"加锁异常====================："+e.getMessage());
            return false;
        }
        finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //阻塞获取锁
    public  void lock(){
        if (trylock())
            return;

        try {
            Thread.sleep(10);
            System.out.println("尝试获取锁...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        lock();
    }


    //释放锁
    public  boolean  unlock(){
        Connection connection = null;
        try{
            connection  = JDBCUtils.getConnection();
            Statement statement = connection.createStatement();

            statement.execute("delete from t_goods_lock where id = "+goodsId);
            System.out.println(Thread.currentThread().getName()+"解锁，删除数据 goodsId="+goodsId);
            return true;
        }catch (Exception e) {
            System.out.println(Thread.currentThread().getName()+"解锁异常====================:"+e.getMessage());
            //e.printStackTrace();
            return false;
        }
        finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
